﻿/**
作者：
 */
package com.zito.pojo;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import com.downlove.cache.CacheManager;
import com.downlove.database.DBException;
import com.downlove.database.POJO;
import com.downlove.database.QueryHelper;

public class AdsPOJO extends POJO {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Object[] valueObj;

	public boolean Update() {
		int tmp = QueryHelper.update(
				_updateSQL("startdate", "enddate", "htmlcode", "files", "url",
						"name", "midea", "id"), this.valueObj);
		if (tmp > 0) {
			Evict(true);
		}
		return true;
	}

	public boolean Active() {
		boolean flag = true;
		String unActive = "UPDATE " + TableName()
				+ " SET active=0 WHERE active=1";
		String onActive = "UPDATE " + TableName() + " SET active=1 WHERE id=?";
		try {
			QueryHelper.setAutoCommit();
			QueryHelper.commitUpdate(unActive);
			QueryHelper.commitUpdate(onActive, this.getId());
			QueryHelper.commit();
		} catch (Exception e) {
			flag = false;
			try {
				QueryHelper.rollback();
			} catch (SQLException e1) {
				throw new DBException(e1);
			}
			throw new DBException(e);
		} finally {
			try {
				QueryHelper.closeTransConnection();
			} catch (SQLException e2) {
				throw new DBException(e2);
			}
		}
		if (this.IsObjectCachedByID())
			CacheManager.evict(CacheRegion(), OBJ_COUNT_CACHE_KEY);
		return flag;
	}

	private String _updateSQL(String... args) {
		Map<String, Object> pojo_bean = this.ListInsertableFields();
		StringBuilder sql = new StringBuilder("UPDATE ");
		sql.append(TableName());
		sql.append(" SET ");
		valueObj = new Object[args.length];
		for (int i = 0; i < args.length - 1; i++) {
			if (i > 0)
				sql.append(',');
			sql.append(args[i] + "=?");
			valueObj[i] = pojo_bean.get(args[i]);
		}
		valueObj[args.length - 1] = pojo_bean.get(args[args.length - 1]);
		// sql.append(" WHERE " + args[args.length-1]
		// +"="+pojo_bean.get(args[args.length-1]));
		sql.append(" WHERE " + args[args.length - 1] + "=?");
		return sql.toString();
	}

	public List<Long> idList(int page, int size) {
		String sql = "SELECT id FROM " + TableName()
				+ " ORDER BY active DESC,id DESC";
		return QueryHelper.queryList(sql, page, size);
	}

	public <T extends POJO> T Get() {
		String sql = "SELECT id FROM " + TableName() + " WHERE active=1";
		Object tmp = QueryHelper.query(sql);
		if (tmp == null)
			return null;
		return Get((Long) tmp);
	}
}
